﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using Traceability.Commont.Domains.AnimalsDomainFiles;
using Traceability.Commont.Domains.BatchManagementFiles;
using Traceability.Commont.DTOs.CommontFiles;
using Traceability.Commont.DTOs.WhiteStripWeighingHtmlGroup;
using Traceability.Commont.Infrastructures.Interfaces;
namespace U.Enterprise.Api.Applications.WhitestripWeighing
{
    public class WhiteStripWeighingHtmlHandler : IRequestHandler<WhiteStripWeighingHtmlCommond, Resqults<WhiteGroupDTO>>
    {


        /// <summary>
        /// 批宰计划
        /// </summary>
        private readonly IBateRepository<BulkSlaughter> _BulkSlaughter;
        /// <summary>
        /// 白条称重
        /// </summary>
        private readonly IBateRepository<WhiteNotes> whit;

        public WhiteStripWeighingHtmlHandler(IBateRepository<BulkSlaughter> bulkSlaughter, IBateRepository<WhiteNotes> whit)
        {
            _BulkSlaughter = bulkSlaughter;
            this.whit = whit;
        }

        public async Task<Resqults<WhiteGroupDTO>> Handle(WhiteStripWeighingHtmlCommond request, CancellationToken cancellationToken)
        {

            var result = new Resqults<WhiteGroupDTO>() { Code = 0 };
            int years = DateTime.Now.Year;
            int months = DateTime.Now.Month;
            if (request.Date != null)
            {
                years = request.Date.Value.Year;
                months = request.Date.Value.Month;
            }
            var list = (from a in _BulkSlaughter.GetAll()
                       join b in whit.GetAll() on a.BulkSlaughterNo equals b.SlaughterNumber
                       where (b.WhiteNoteTime.Year == years && b.WhiteNoteTime.Month == months)
                       group new { a, b } by new { b.WhiteNoteTime.Day } into c
                       select new WhiteGroupDTO()
                       {
                           Nums = c.Sum(x => x.a.BulkSlaughterNum),
                           WeghitNums = c.Sum(x => x.b.WhiteNoteNum),
                           WightSum = c.Sum(x => x.b.NetWeight),
                           day = c.Key.Day
                       }).ToList();
            result.Date = list;
            return result;
        }
    }
}
